<script>
	// H5所需sdk  不用就删掉   package.json也删掉，不然会影响小程序的打包大小
	// #ifdef  H5
	import TIM from 'tim-js-sdk/tim-js-friendship.js';
	import COS from 'cos-js-sdk-v5';
	// import {
	// 	TUICallKit,
	// 	TUICallKitServer,
	// 	VideoDisplayMode,
	// 	VideoResolution,
	// 	STATUS
	// } from "@tencentcloud/call-uikit-vue2.6";
	// #endif	



	// #ifdef MP-WEIXIN  || APP-PLUS
	import TIM from 'tim-wx-sdk/tim-wx-friendship.js';
	import COS from 'cos-wx-sdk-v5';
	// #endif

	let sdkAppID = 1400800054;

	// // APP通话插件
	// #ifdef  APP-PLUS
	// const TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit');
	// TUICallKit.enableFloatWindow(true);
	// console.log(TUICallKit, '通话初始化TUICallKit ｜ ok');
	// #endif
	import Vue from 'vue';

	// import {
	// 	genTestUserSig
	// } from '../debug/GenerateTestUserSig.js';

	import {
		genTestUserSig
	} from '@/im/debug/GenerateTestUserSig.js'
	
	import config from '@/common/config.js'

	export default {
		onLaunch() {
			Vue.prototype.TIM = TIM;
			const compensateHeight = 10; //非刘海屏状态栏高度偏低，补充10
			uni.getSystemInfo({
				success: (e) => {
					// 获取手机状态栏高度
					let statusBar = e.statusBarHeight
					let customBar
					// #ifndef MP
					customBar = statusBar + (e.platform == 'android' ? 50 : 45)
					// #endif
					// #ifdef MP-WEIXIN
					// 获取胶囊按钮的布局位置信息
					let menu = wx.getMenuButtonBoundingClientRect()
					// 导航栏高度 = 胶囊下距离 + 胶囊上距离 - 状态栏高度
					customBar = menu.bottom + menu.top
					// #endif
					// #ifdef MP-ALIPAY
					customBar = statusBar + e.titleBarHeight
					// #endif
					this.$store.commit("SET_STATUSBAR", {
						statusBar: statusBar + compensateHeight,
						customBar: customBar + compensateHeight
					})
				}
			})
			// #ifdef APP-PLUS
			plus.runtime.getProperty(plus.runtime.appid, (info) => {
				this.versionName = info.version;
				this.globalData.versionName = info.version;
			});
			// #endif
			this.initialization();
			uni.setStorageSync('ispayflg', "1");
			this.menpiaoData();
		},
		onUnload() {
			console.log('onUnload');
			clearInterval(this.timer);
			clearInterval(this.timers);
			clearInterval(this.timers1);
			clearInterval(this.timers3);
		},
		onHide() {
			clearInterval(this.timers3);
			setTimeout(() => {
				uni.setStorageSync('ispayflg', "1");
			}, 10000);
			//console.log('onHide**************777***');
		},
		onShow: function(options) {
			let query = options.query;
			console.log(JSON.stringify(query) + '*******6666666666666666666******');
			if (query.userId) {
				// #ifdef MP-WEIXIN
				this.wxlogon();
				// #endif 
				uni.setStorageSync('queryname', query);
				//console.log('************665555*****');
				this.timers3 = setInterval(() => {
					this.apppushwxpay(query);;
				}, 2000);
			} else {
				// #ifdef  APP-PLUS
				this.initialization();
				this.timers = setInterval(() => {
					this.checkUpdate();
				}, 2000);
				// #endif

				// #ifdef MP-WEIXIN
				this.timers = setInterval(() => {
					this.wxjosn();
				}, 2000);
				this.wxlogon();
				this.timers1 = setInterval(() => {
					this.codelogin();
				}, 2000);
				// #endif
				this.sensitive();
			}
		},
		globalData: {
			userInfo: null,
			userProfile: null,
			webviewUrl: '',
			headerHeight: 0,
			statusBarHeight: 0,
			deviceModel: 'iphone',
			versionName: '',
		},
		methods: {
			async apppushwxpay(options) {
				 console.log(JSON.stringify(options)+'*******888444****');
				let wxopenid = uni.getStorageSync('wxopenid');
				if (!wxopenid) {
					return;
				}
				clearInterval(this.timers3);
				let ispayflg = uni.getStorageSync('ispayflg');
				if (ispayflg == '2') {
					return;
				}
				let postParam = {};
				postParam.userId = options.userId;
				postParam.openid = wxopenid;
				postParam.price = options.price;
				postParam.type = options.type;
				postParam.appId = 'wxff095378edaf00da';
				postParam.projectId = options.projectId;
				// postParam.token =options.token;

				 console.log(JSON.stringify(postParam)+'*******66666333****');	
				 //192.168.2.218  api.ptszyxx.com
				uni.request({
					url: 'https://api.ptszyxx.com/api/JsApiController/recharge',
					method: 'POST',
					data: postParam,
					header: {
						'content-type': 'application/x-www-form-urlencoded', //自定义请求头信息
						// 'token':options.token,
					},
					success: (res) => {
						console.log('*******88888*****' + JSON.stringify(res));
						let timeStamp = res.data.data.timeStamp;
						let paySign = res.data.data.paySign;
						let appId = res.data.data.appId;
						let signType = res.data.data.signType;
						let nonceStr = res.data.data.nonceStr;                      
						wx.requestPayment({
							"timeStamp": timeStamp,
							"nonceStr": nonceStr,
							"package": res.data.data.package,
							"signType": signType,
							"paySign": paySign,
							"success": function(res) {
								console.log('*************成功' + JSON.stringify(res));
								//uni.setStorageSync('ispayflg', "2");	
								//uni.setStorageSync('userVip', 1);
								//uni.setStorageSync('ispayflg', "3");
								uni.setStorageSync('zhifusuccess', "1");
								uni.showToast({
									title: '支付成功',
									duration: 3000
								})								
							},
							"fail": function(res) {
								//uni.setStorageSync('ispayflg', "1");
								console.log('*************失败' + JSON.stringify(res));
							},
							"complete": function(res) {
								uni.setStorageSync('ispayflg', "2");
								//uni.setStorageSync('ispayflg', "3");
								//console.log('********888888*****complete');

								console.log(res.errMsg);
								 if (res.errMsg == 'requestPayment:ok') {
									 
								    uni.exitMiniProgram({
								    	success: function(res) {
								    		console.log('退出')
								    	},
								    	fail: function(res) {
								    		console.log('失败')							
								    	}
								    })									
								 }

							}
						})
					}
				})

				// console.log(userInfo);
				// this.postParam.userId = userInfo.id;
				// //this.postParam.price = this.data.price;
				// //this.postParam.price ='0.01';
				// this.postParam.openid = wxopenid;	
				// this.postParam.projectId = this.projectId;
				// //192.168.2.218:80  api.ptszyxx.com
				// console.log(JSON.stringify(this.postParam)+'*******');



			},
			exitout()
			{
				uni.exitMiniProgram({
					success: function(res) {
						console.log('退出')
					},
					fail: function(res) {
						console.log('失败')
					}
				})
			},

			sensitive() {
				let now = new Date().getTime();
				let urlstr = "http://zhiyuapp.oss-cn-fuzhou.aliyuncs.com/sensitive/data.json?t=" + now;
				uni.request({
					url: urlstr,
					success: (res) => {
						// console.log('~~~~~~~~~~'+JSON.stringify(res.data));
						uni.setStorageSync('sensitive', res.data);

					}
				})
			},
			wxjosn() {
				let now = new Date().getTime();
				let urlstr = "https://zhiyuapp.oss-cn-fuzhou.aliyuncs.com/uniapp/wxaitaaConfig.json?t=" + now;
				//console.log('~~~~~~~~~~' + urlstr);
				uni.request({
					url: urlstr,
					success: (res) => {
						clearInterval(this.timers);
						console.log('~~~~~~~~~~' + res.data);
						let isaliPay = res.data.isaliPay; //isaliPay 1为开启
						let vipManage = res.data.vipManage; // 1 关闭门票
						let iswx = res.data.iswx; //小程序微信隐藏
						let ticketPrice = res.data.ticketPrice; //门票价格
						let isshipin = res.data.isshipin; //门票价格
						let qianbao = res.data.qianbao;
						let vipopen = res.data.vipopen;

						console.log(vipManage + '****************' + isaliPay + 'iswx:' + iswx);
						uni.setStorageSync('isaliPay', isaliPay);
						uni.setStorageSync('vipManage', vipManage);
						uni.setStorageSync('iswx', iswx);
						uni.setStorageSync('ticketPrice', ticketPrice);
						uni.setStorageSync('isshipin', isshipin);
						uni.setStorageSync('qianbao', qianbao);
						uni.setStorageSync('vipopen', vipopen);
						// if (res.data.open == "1" && res.data.vss != this.versionName) {
						// 	plus.nativeUI.showWaiting("检测更新~~~");
						// 	this.downloadWgt(res.data.wgtUrl);
						// }
					}
				})
			},
			async wxlogon() {
				wx.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: async function(event) {
						const {
							code
						} = event

						if (!event.code) {
							//	console.log('****333333333333333****');
							uni.showModal({
								title: '提示',
								content: '您还未微信授权请先授权',
								confirmText: '去设置',
								success: (res) => {
									if (res.confirm) {
										wx.openSetting();
									} else {
										wx.openSetting();
									}
								}
							});
						}
						//console.log(JSON.stringify(event) + '****77788889867678889****' + event.code);
                       //192.168.2.218   api.ptszyxx.com
						wx.request({
							url: 'https://api.ptszyxx.com/app/wxLogin/loginWx', //仅为示例，并非真实接口地址。
							method: 'GET',
							data: {
								jsCode: event.code,
								"xcc": "aitaa"
							},
							success: (res) => {
								//获得token完成登录
								console.log('获得token完成登录' + JSON.stringify(res));
								// console.log('token********' + res.data.data.token);

								// console.log('status********' + res.data.status + '******' + res
								// 	.data.data.openid);
								uni.setStorageSync('wxopenid', res.data.data.openid);

								// this.codelogin();
								// if (res.data.data.token) {
								// 	uni.setStorageSync('rongcloud_token', res.data.data
								// 		.rongcloud_token);
								// 	uni.setStorageSync('token', res.data.data.token);
								// 	uni.setStorageSync('user', res.data.data.user);
								// 	// uni.removeStorageSync('noregist');
								// 	uni.setStorageSync('noregist', '2');
								// } else {
								// 	uni.setStorageSync('noregist', '1');
								// }
							}
						});
					},
				})
			},
			async codelogin() {
				clearInterval(this.timers);
				const userID = uni.getStorageSync('userID');
				if (userID) {
					clearInterval(this.timers1);
					//return;
				}
				let openid = uni.getStorageSync('wxopenid');

				let res = await this.$c.post('/app/login/login?loginname=' + openid +
					'&code=708090&loginType=2');
				if (res.code != 0) {
					return;
				}
				clearInterval(this.timers1);
				// if (res.code == 0) {
				// 	clearInterval(this.timers1);
				// }
				//console.log(JSON.stringify(res.data.user) + '********5*****5***5**');
				// let token = res.data.token

				let ten = res.data.user.tengxuncode.toString();
				let usrifo = res.data.user;
				// let userID = res.data.user.tengxuncode.toString();
				let userSig = genTestUserSig(ten).userSig;
				uni.setStorageSync('token', res.data.token);
				let iswanshan = res.data.user.iswanshan;
				uni.setStorageSync('iswanshan', iswanshan);
				uni.setStorageSync('userSig', userSig);
				uni.setStorageSync('userID', ten);
				uni.setStorageSync('userInfo', usrifo);
				this.isLogin();
				let query = uni.getStorageSync('queryname');
				let iswx= uni.getStorageSync('iswx');	
				if (!query.type) {
					if (iswanshan == 2 && iswx==1) {
						uni.navigateTo({
							url: '/pages/register/registers'
						})
					}
				}


			},
			//版本更新
			checkUpdate() {
				if (plus) {
					plus.runtime.getProperty(plus.runtime.appid, (info) => {
						this.versionName = info.version;
					});
					let now = new Date().getTime();
					let urlstr = "https://zhiyuapp.oss-cn-fuzhou.aliyuncs.com/uniapp/uniapp.json?t=" + now;
					uni.request({
						url: urlstr,
						success: (res) => {
							clearInterval(this.timers);
							let isaliPay = res.data.data.isaliPay; //isaliPay 1为开启
							let vipManage = res.data.data.vipManage; // 1 关闭门票
							let ticketPrice = res.data.data.ticketPrice; //门票价格
							
							let vipopen =res.data.data.vipopen;
							let xiaochengpay =res.data.data.xiaochengpay;							
							let wxappid =res.data.data.wxappid;
							let secret =res.data.data.secret;
							let qianbao = res.data.data.qianbao;
							uni.setStorageSync('isaliPay', isaliPay);
							uni.setStorageSync('isWxpay', res.data.data.isWxpay);
							uni.setStorageSync('vipManage', vipManage);
							uni.setStorageSync('ticketPrice', ticketPrice);
							
							uni.setStorageSync('wxappid', wxappid);
							uni.setStorageSync('secret', secret);
							uni.setStorageSync('vipopen', vipopen);
							uni.setStorageSync('xiaochengpay', xiaochengpay);
								uni.setStorageSync('qianbao', qianbao);

							if (res.data.data.open == "1" && res.data.data.vss != this.versionName) {
								this.downloadWgt(res.data.data.wgtUrl);
							}
						}
					})
				}
			},
			//wgt下载安装
			downloadWgt(wgtUrl) {
				if (plus) {
					plus.downloader.createDownload(wgtUrl, {
						filename: "_doc/update/"
					}, function(d, status) {
						console.log(d);
						console.log(status);
						if (status == 200) {
							plus.runtime.install(d.filename, {
								force: true
							}, function() {
								plus.nativeUI.closeWaiting();
								plus.runtime.restart();
								// plus.nativeUI.alert("更新成功~~~", function() {
								// 	plus.runtime.restart();
								// });
							}, function(e) {
								plus.nativeUI.closeWaiting();
								plus.nativeUI.alert("更新失败~~~ [" + e.code + "]：" + e.message);
							});
						} else {
							plus.nativeUI.alert("下载wgt失败！");
							plus.nativeUI.closeWaiting();
						}
					}).start();
				}
			},
			// 初始化 im
			initialization() {
				const sdkID = uni.getStorageSync('sdkAppID');
				if (sdkID) {
					sdkAppID = sdkID;
				}

				// 初始化tim
				uni.$TUIKit = TIM.create({
					SDKAppID: sdkAppID
				});
				wx.$TUIKit = uni.$TUIKit;

				// #ifdef  H5
				uni.$TUIKit.registerPlugin({
					'cos-js-sdk': COS
				});
				// #endif

				// #ifdef  APP-PLUS || MP-WEIXIN
				uni.$TUIKit.registerPlugin({
					'cos-wx-sdk': COS
				});
				// #endif

				// #ifdef  H5
				uni.$TUICallKitView = TUICallKit;
				uni.$TUICallKit = TUICallKitServer;
				// #endif

				// #ifdef  APP-PLUS
				// uni.$TUICallKit = TUICallKit;
				uni.$TUICallKit = {
					login() {},
					groupCall() {},
					call() {}
				}

				// #endif

				uni.$TUIKit.setLogLevel(3);

				uni.$TUIKitTIM = TIM;
				uni.$TUIKitEvent = TIM.EVENT;
				uni.$TUIKitVersion = TIM.VERSION;
				uni.$TUIKitTypes = TIM.TYPES; // 监听系统级事件
				uni.$resetLoginData = this.resetLoginData();

				uni.$TUIKit.on(uni.$TUIKitEvent.SDK_NOT_READY, this.onSdkNotReady);
				uni.$TUIKit.on(uni.$TUIKitEvent.KICKED_OUT, this.onKickedOut);
				uni.$TUIKit.on(uni.$TUIKitEvent.ERROR, this.onTIMError);
				uni.$TUIKit.on(uni.$TUIKitEvent.NET_STATE_CHANGE, this.onNetStateChange);
				uni.$TUIKit.on(uni.$TUIKitEvent.SDK_RELOAD, this.onSDKReload);
				uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady);

				// 是否登录
				this.isLogin();
			},
			isLogin() {
				const userID = uni.getStorageSync('userID');
				const userSig = uni.getStorageSync('userSig');
				const userInfo = uni.getStorageSync('userInfo');
				let token = uni.getStorageSync('token');
				console.log("============", userID, "==========" + token)
				if (!userID || !token) {
					uni.reLaunch({
						url: '/im/login/login'
					});
				} else {
					// 登录im
					uni.$TUIKit
						.login({
							userID: userID,
							userSig: userSig
						})
						.then(res => {
							console.log('IM登录成功', res);
						})
						.catch(() => {});

					// 登录 native 原生通话插件
					// #ifdef  H5
					uni.$TUICallKit.init({
							SDKAppID: sdkAppID,
							userID: userID,
							userSig: userSig
						},
						res => {
							if (res.code === 0) {
								console.log('app视频通话登录成功');
							} else {
								console.log(`app视频通话, error message = ${res.msg}`);
							}
						}
					);
					// #endif
					// #ifdef  APP-PLUS
					uni.$TUICallKit.login({
							SDKAppID: sdkAppID,
							userID: userID,
							userSig: userSig
						},
						res => {
							if (res.code === 0) {
								console.log('app视频通话登录成功');
							} else {
								console.log(`app视频通话, error message = ${res.msg}`);
							}
						}
					);
					// #endif
				}
			},
			// TODO:
			resetLoginData() {
				this.globalData.expiresIn = '';
				this.globalData.sessionID = '';
				this.globalData.userInfo = {
					userID: '',
					userSig: '',
					token: '',
					phone: ''
				};
				this.globalData.userProfile = null;
			},
			onTIMError() {},
			onNetStateChange() {},
			onSDKReload() {},
			onSDKReady() {
				console.log('im-onSDKReady');
				this.$store.commit('login');
			},
			onSdkNotReady() {},
			onKickedOut() {
				setTimeout(() => {
					uni.showToast({
						title: '您被踢下线',
						icon: 'error'
					});
				}, 1000);
				uni.reLaunch({
					url: '/im/login/login'
				});
			},
			menpiaoData() {
				//没有登录
				const userID = uni.getStorageSync('userID');
				let token = uni.getStorageSync('token');
				if (!userID || !token) {
					return
				} 
				uni.request({
					url: config.production + '/app/tickUserInfo/info',
					header:{
						token: token
					},
					success: (result) => {
						console.log("门票："+ JSON.stringify(result))
						const res = result.data;
						if (res.code == 0) {
							if (res.data.windowTicket != 1) {
								uni.reLaunch({
									url: '/im/login/menpiao'
								});
							}
						}
					}
				})
			},
		}
	};
</script>

<style lang="scss">
	@import '@/iconfont/iconfont.css';
	@import 'uview-ui/index.scss';
	@import 'static/css/index.css';
	@import 'static/css/globa.scss';
</style>